# -*- coding: utf-8 -*-
from django.http import HttpResponse
from django.forms.models import model_to_dict
from jiazheng.models import Menus, MenusIntro, ThirdLogin, SystemAd
from tongxiaoyong_com.settings import WX_CONFIG
from urllib import request
import json
from django.shortcuts import render

"""
是否自定变量
"""
def isset(v): 
    try : 
        type(eval(v))
        return True
    except : 
        return  None 


"""
转json输出
"""
def toJson(data):
    return json.dumps(data, ensure_ascii=False)

"""
菜单列表
"""
def getList(request):
    hot_services = []
    ad_banners = []
    summary = []
    menus = Menus.objects.filter(menu_type=2).all().order_by('sort')
    i = 0
    for val in menus:
        menu_dict = model_to_dict(val, exclude=['create_date'])
        if i == 0:
            menu_intrs = MenusIntro.objects.filter(menu_id_id=val.id, type=1).all().order_by('sort')[:1]
            for menu_intr in menu_intrs:
                summary.append(model_to_dict(menu_intr, exclude=['create_date']))
        i = i+1
        hot_services.append(menu_dict)

    ads = SystemAd.objects.filter(status=0).all().order_by('sort')
    for ad in ads:
        ad_banners.append(model_to_dict(ad, exclude=['create_date']))
        
    list = {"ad_banners" : ad_banners, "hot_services":hot_services, "summary":summary}   
    return HttpResponse(toJson(list))

"""
菜单摘要
"""
def getSummary(request):
    list = []
    menu_id = request.GET.get('menu_id',0)
    menu_instrs = MenusIntro.objects.filter(menu_id_id=menu_id).all().order_by('sort')
    for val in menu_instrs:
        d = model_to_dict(val, exclude=['create_date'])
        list.append(d)
    
    return HttpResponse(toJson({"summary":list}))

"""
菜单说明
"""
def getDetail(request):
    list = []
    menu_id = request.POST.get('menu_id',0)
    menu_instrs = MenusIntro.objects.filter(menu_id=menu_id).all().order_by('sort')
    for val in menu_instrs:
        d = model_to_dict(val, exclude=['create_date'])
        list.append(d)
    
    return HttpResponse(toJson({"list":list}))

"""
小程序授权信息
"""
def getToken(request):
    app = request.GET.get('app', 'wx')
    code = request.GET.get('code', None)
    
    if app == "wx" and code:
        url = 'https://api.weixin.qq.com/sns/jscode2session?appid=%s&secret=%s&js_code=%s&grant_type=authorization_code' % (WX_CONFIG['APPID'],WX_CONFIG['APPSECRET'],code)
        content = urlGet(url, {})
        res = json.loads(content);
        if 'openid' in res.keys():
            userInfo = ThirdLogin.objects.filter(open_id=res['openid'], app=app).first()
            if not userInfo:
                userInfo = ThirdLogin()
            userInfo.app = app
            userInfo.open_id = res['openid']
            userInfo.session_id = res['session_key']
            userInfo.save()
            return ajaxOut()
        
        return ajaxOut(res['errmsg'], res['errcode'])
        
"""
接口请求
"""        
def urlGet(url, data):
    header = {}
    data = None
    rq = request.Request(url, data = data, headers = header)
    res = request.urlopen(rq, timeout=3);
    respoen = res.read();
    result = str(respoen, encoding = "utf-8")
    return result

"""
统一输出格式
"""
def ajaxOut(msg = 'success', errCode = 0):
    return HttpResponse(toJson({"msg":msg,"errorCode":errCode}))

def index(request):
    return render(request, 'index.html', {})